﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;


    public class AttributeHelper ///属性类
{

    /// <summary>
    /// 获取映射表名
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static string GetTName(Type type)
    {
        string tableName = string.Empty;
        //获取指定类型的自定义特性
        object[] attrs = type.GetCustomAttributes(false);
        foreach (var attr in attrs)
        {
            if (attr is TableAttribute)
            {
                TableAttribute tableAttribute = attr as TableAttribute;
                tableName = tableAttribute.TableName;
            }
        }
        if (string.IsNullOrEmpty(tableName))
        {
            tableName = type.Name;
        }
        return tableName;
    }

    /// <summary>
    /// 获取映射列名
    /// </summary>
    /// <param name="property"></param>
    /// <returns></returns>
    public static string GetColName(PropertyInfo property)
    {
        string columnName = string.Empty;
        //获取指定类型的自定义特性
        object[] attrs = property.GetCustomAttributes(false);
        foreach (var attr in attrs)
        {
            if (attr is ColumnAttribute)
            {
                ColumnAttribute colAttr = attr as ColumnAttribute;
                columnName = colAttr.ColumnName;
            }
        }
        if (string.IsNullOrEmpty(columnName))
        {
            columnName = property.Name;
        }
        return columnName;
    }

    ///<summary>  
    /// 获取主键名  
    /// </summary>  
    /// <param name="type"></param>  
    /// <returns></returns>  
    public static string GetPrimary(Type type)
    {
        object[] attributes = type.GetCustomAttributes(false);
        foreach (var attr in attributes)
        {
            if (attr is PrimaryKeyAttribute)
            {
                PrimaryKeyAttribute primaryKeyAttr = attr as PrimaryKeyAttribute;
                return primaryKeyAttr.PrimaryKey;
            }
        }
        return null;
    }

}